package com.example.gateway.config;

import com.alibaba.nacos.common.utils.IoUtils;
import com.example.common.api.ResultCode;
import com.example.common.constant.SecurityConstants;
import com.example.common.util.ResponseErrorUtil;
import com.example.gateway.authorization.AuthorizationManager;
import com.example.gateway.filter.IgnoreUrlsRemoveJwtFilter;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import reactor.core.publisher.Mono;

import java.io.InputStream;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.stream.Collectors;

@AllArgsConstructor
@Configuration
@EnableWebFluxSecurity
@Slf4j
public class ResourceServerConfig {

    private final IgnoreUrlConfig ignoreUrlConfig;
    private final IgnoreUrlsRemoveJwtFilter ignoreUrlsRemoveJwtFilter;
    private final AuthorizationManager authorizationManager;

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity httpSecurity){
        log.info("urls: " + ignoreUrlConfig.getUrls().stream().map(String::toString).collect(Collectors.joining(",")));
        httpSecurity.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter()).publicKey(rsaPublicKey());
        // 自定义处理JWT请求过期或者签名错误的结果
        httpSecurity.oauth2ResourceServer().authenticationEntryPoint(authenticationEntryPoint());
        // 对白名单路径，直接移除JWT请求头
        httpSecurity.addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
        httpSecurity.authorizeExchange()
                .pathMatchers(ignoreUrlConfig.getUrls().stream().map(String::toString).collect(Collectors.joining(","))).permitAll()
                .anyExchange().access(authorizationManager)  //鉴权管理器配置
                .and().exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler())  //处理未授权
                .authenticationEntryPoint(authenticationEntryPoint())  //处理未认证
                .and().csrf().disable();

        return httpSecurity.build();
    }

    @Bean
    public ServerAccessDeniedHandler accessDeniedHandler(){
        return (exchange, denied) -> Mono.defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response-> ResponseErrorUtil.writeErrorMessage(response, ResultCode.FORBIDDEN));
    }

    @Bean
    public ServerAuthenticationEntryPoint authenticationEntryPoint(){
        return (exchange, ex) -> Mono.defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response -> ResponseErrorUtil.writeErrorMessage(response, ResultCode.UNAUTHORIZED));
    }

    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix(SecurityConstants.AUTHORITY_PREFIX);
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(SecurityConstants.JWT_CLAIM_NAME);
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }

    /**
     * 读取本地公共的JWT验证公匙
     * */
    @SneakyThrows
    @Bean
    public RSAPublicKey rsaPublicKey(){
        Resource resource = new ClassPathResource("public.key");
        InputStream inputStream = resource.getInputStream();
        String publicKeyData = IoUtils.toString(inputStream, "UTF-8");

        byte[] bytes = Base64.getMimeDecoder().decode(publicKeyData);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

}
